﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;
using IFactory;
using System.IO;
using System.Collections.Generic;

public partial class SpecialPlan_SpecialPlanDisplany : System.Web.UI.Page
{
    Authentication dllAuthentication = new Authentication();
    Model.UserInfo objUserInfo = new Model.UserInfo();
    DataTable _powerTable = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dllAuthentication.isLogin();


        Page.RegisterStartupScript("getheighandwidth", "<script>document.getElementById('h1h').value=window.screen.availHeight;document.getElementById('h2w').value= window.screen.width ;</script>");


        //得到月计划信息  
        if (!IsPostBack)
        {

            #region 弹出提醒
            PopupManager dllPopupManager = new PopupManager();
            string _info = dllPopupManager.getPopupInfo();
            if (_info.Length > 0)
            {
                ShowMessage(_info);
            }
            #endregion
            //绑定本月计划           
            bindDropDownList(this.drpDepartment);
            bindGridView();
        }
        //判断是否为经理，非经理锁定部门选择框
        this.drpDepartment.Enabled = false;
        int _isManager = dllAuthentication.IsManager(objUserInfo.UserName);
        if (_isManager > 0)
        {
            this.drpDepartment.Enabled = true;
            this.btnToExcel.Visible = true;
        }
        else
        {
            this.drpDepartment.Enabled = false;
            this.btnToExcel.Visible = false;
        }
    }

    /// <summary>
    /// 弹出小窗体事件
    /// </summary>
    /// <param name="msg"></param>
    public void ShowMessage(string msg)
    {
        EeekSoft.Web.PopupWin pop = new EeekSoft.Web.PopupWin();
        this.Controls.Add(pop);
        pop.Text = msg;
        pop.Message = msg;
        pop.Title = System.Configuration.ConfigurationManager.AppSettings["CompanyName"].ToString();
        pop.WindowScroll = true;
        pop.HideAfter = 99999999;
        pop.DockMode = EeekSoft.Web.PopupDocking.BottomLeft;
        pop.OffsetX = int.Parse(Session["_width"].ToString()) - 400;
        pop.ActionType = EeekSoft.Web.PopupAction.MessageWindow;
        pop.OffsetY = 1;
        pop.Width = 220;
        pop.Height = 170;
    }

    /// <summary>
    /// 根据逗号换行事件
    /// </summary>
    public string wrapByComma(string str)
    {
        string _content = string.Empty;
        _content = str.Replace("&lt;br&gt;", "<br>");
        //_gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&gt;", ">");
        _content = str.Replace(",", "<br>");
        return _content;

    }

    /// <summary>
    /// 绑定所有的dropdownlist
    /// </summary>
    /// <param name="_drp"></param>
    void bindDropDownList(DropDownList _drp)
    {
        //部门绑定
        if (_drp.Equals(this.drpDepartment))
        {
            this.drpDepartment.DataSource = new BLL.DepartmentInfoManager().getNoTree();
            this.drpDepartment.DataTextField = "DepartmentName";
            this.drpDepartment.DataValueField = "DepartmentId";
            this.drpDepartment.DataBind();
            ListItem _li = new ListItem("请选择部门");
            this.drpDepartment.Items.Insert(0, _li);
            object[] _value = new object[1];
            _value[0] = objUserInfo.UserName;
            DataTable _userTable = new BLL.UserInfoManager().get(UserInfoManager.field.UserName.ToString(), _value);
            if (_userTable.Rows.Count > 0)
            {
                this.drpDepartment.SelectedIndex = this.drpDepartment.Items.IndexOf(this.drpDepartment.Items.FindByText(_userTable.Rows[0]["DepartmentId"].ToString()));

            }
            if (Request.QueryString["Department"] != null)
            {
                this.drpDepartment.SelectedIndex = this.drpDepartment.Items.IndexOf(this.drpDepartment.Items.FindByValue(Request.QueryString["Department"].ToString()));
            }
        }
    }


    /// <summary>
    /// 绑定gridview事件
    /// </summary>
    void bindGridView()
    {
        object[] _value = new object[1];
        _value[0] = this.drpDepartment.SelectedItem.Text;
        DataTable dt = new BLL.SpecialPlan().GetSpecialPlanByDepartment(_value);
        this.rptSpecialPlan.DataSource = dt;
        this.rptSpecialPlan.DataBind();
    }


    /// <summary>
    /// 根据逗号换行事件
    /// </summary>
    void wrapByComma(GridView _gridView, int _rowIndex, int _cells)
    {
        string _content = _gridView.Rows[_rowIndex].Cells[_cells].Text;
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&lt;br&gt;", "<br>");
        //_gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&gt;", ">");
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _gridView.Rows[_rowIndex].Cells[_cells].Text.Replace(",", "<br>");


    }

    /// <summary>
    /// 部门项改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGridView();
    }


    ///   <summary>   
    ///   文件下载   
    ///   </summary>   
    ///   <param   name="FullFileName"></param>   
    private void FileDownload(string strFileName)
    {

        FileInfo DownloadFile = new FileInfo(strFileName);
        if (!DownloadFile.Exists)
        {
            Utility.HttpHelp.alert("无附件,请与管理员联系", Page);
            return;
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = false;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName.Substring(strFileName.LastIndexOf('\\') + 1), System.Text.Encoding.UTF8));
        // Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

        Response.WriteFile(DownloadFile.FullName);
        Response.Flush();
        Response.End();

    }

    /// <summary>
    /// 导出excel
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnToExcel_Click(object sender, EventArgs e)
    {
        object[] _value = new object[1];
        _value[0] = this.drpDepartment.SelectedItem.Text;
        DataTable dt = new BLL.SpecialPlan().GetSpecialPlanByDepartment(_value);
        this.gdvSpecialPlan.DataSource = dt;
        this.gdvSpecialPlan.DataBind();
        GridView[] _gridView = new GridView[1];
        _gridView[0] = this.gdvSpecialPlan;
        Utility.Comm.SpecialToExcel(GridViewToDataTable(_gridView), this.drpDepartment.SelectedItem.Text);

    }

    /// <summary>
    /// GridView转DataTable
    /// </summary>
    DataTable[] GridViewToDataTable(GridView[] _sourceGridView)
    {
        DataTable[] _targetDataTable = new DataTable[_sourceGridView.Length];
        for (int i = 0; i < _targetDataTable.Length; i++)
        {
            _targetDataTable[i] = new DataTable();
            DataColumn dc = new DataColumn();
            //根据源GridView循环创建目标DataTable列
            for (int j = 0; j < _sourceGridView[i].Columns.Count; j++)
            {
                if (_sourceGridView[i].Columns[j].Visible == true)
                {
                    dc = new DataColumn(_sourceGridView[i].Columns[j].HeaderText);
                    _targetDataTable[i].Columns.Add(dc);
                }
            }
            //根据源GridView循环创建目标DataTable行
            for (int j = 0; j < _sourceGridView[i].Rows.Count; j++)
            {
                DataRow dr = _targetDataTable[i].NewRow();
                for (int k = 0; k < _sourceGridView[i].Columns.Count; k++)
                {

                    if (_sourceGridView[i].Columns[k].Visible == true && k < _targetDataTable[i].Columns.Count)
                    {
                        if (_sourceGridView[i].Columns[k].HeaderText == "计划来源")
                        {
                            LinkButton lbtn = (LinkButton)_sourceGridView[i].Rows[j].Cells[k].FindControl("lbtnSource");
                            dr[k] = lbtn.Text;
                        }
                        else
                        {
                            dr[k] = _sourceGridView[i].Rows[j].Cells[k].Text;
                        }

                    }

                }
                _targetDataTable[i].Rows.Add(dr);
            }

        }
        return _targetDataTable;
    }

    /// <summary>
    /// 流程事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnFlow_Click(object sender, EventArgs e)
    {
        int _count = 0;
        int _SpecialPlanId = 0;
        int type = -1;//1 上月工作情况 2 本月工作情况 3上月未完成工作  4 持续进行工作
        //上月工作情况
        for (int i = 0; i < this.gdvSpecialPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvSpecialPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                if (this.gdvSpecialPlan.DataKeys[i]["Id"] != null && this.gdvSpecialPlan.DataKeys[i]["Id"].ToString().Length != 0)
                {
                    _SpecialPlanId = Convert.ToInt32(this.gdvSpecialPlan.DataKeys[i]["Id"].ToString());
                    _count++;
                    type = 1;
                }
            }
        }

        if (_count == 1)
        {
            //判断是否为评估人，如果该条计划的评估人是当前用户则不能修改该条计划

            string _url = "../WebCommon/VerifyCircruitDisplay.aspx?PlanId=" + _SpecialPlanId + "&PlanType=6";
            Page.RegisterStartupScript("windowOpen",
               "<script language=javascript>window.open('" + _url + "','quarterplandetailmodify','height=150,width=550,top=250,left=300,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");

        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能查看一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
    }



    /// <summary>
    /// 修改专项
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnModifySpecialPlan_Click(object sender, EventArgs e)
    {
        string department = drpDepartment.SelectedItem.Value;

        int _count = 0;
        int _SpecialPlanId = 0;
        for (int i = 0; i < this.gdvSpecialPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvSpecialPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                if (this.gdvSpecialPlan.DataKeys[i]["Id"] != null && this.gdvSpecialPlan.DataKeys[i]["Id"].ToString().Length != 0)
                {
                    _SpecialPlanId = Convert.ToInt32(this.gdvSpecialPlan.DataKeys[i]["Id"].ToString());
                    _count++;
                }
            }
        }
        if (_count == 1)
        {
            //判断是否计划二次评估完成， 评估完成不允许修改。
            object[] _value = new object[1];
            _value[0] = _SpecialPlanId;
            DataTable SpecialPlan = new BLL.SpecialPlan().GetSpecialPlanById(_value);
            if (SpecialPlan.Rows.Count == 0)
            {
                if (Convert.ToInt32(SpecialPlan.Rows[0]["State"]) >= 4 && Convert.ToInt32(SpecialPlan.Rows[0]["State"]) != 9)
                {
                    Utility.HttpHelp.alert("计划已二次评估完成，不允许修改！", Page);
                    return;
                }
            }

            string _url = "ModifySpecialPlan.aspx?Id=" + _SpecialPlanId + "&url=SpecialPlanList.aspx&Department=" + department;
            Page.RegisterStartupScript("windowopen", "<script>window.open('" + _url + "','','height=200,width=1000,top=300,left=20,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');</script>");
            return;
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能修改一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
    }


    protected void rptSpecialPlan_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            HiddenField HSpecialPlanId = e.Item.FindControl("HSpecialPlanId") as HiddenField;
            Repeater rep = e.Item.FindControl("rptSpecialPlanDetail") as Repeater;//找到里层的repeater对象
            Label lblAlert = e.Item.FindControl("lblAlert") as Label;
            Button btnDownLoad = e.Item.FindControl("btnDownLoad") as Button;
            HiddenField HAttachmengPath = e.Item.FindControl("HAttachmengPath") as HiddenField;
            HiddenField Hstate = e.Item.FindControl("Hstate") as HiddenField;
            if (HAttachmengPath.Value.Length > 0)
            {
                lblAlert.Visible = false;
                btnDownLoad.Visible = true;
            }
            else
            {
                lblAlert.Visible = true;
                btnDownLoad.Visible = false;
            }
            HtmlTableRow tr = e.Item.FindControl("row") as HtmlTableRow;
            switch (Convert.ToInt32(Hstate.Value))
            {
                case 4:
                    tr.Style.Add("background-color", "#00C0C0");
                    break;
                case 5:
                    tr.Style.Add("background-color", "#00C000");
                    break;
                case 6:
                    tr.Style.Add("background-color", "#ffff00");
                    break;
                case 7:
                    tr.Style.Add("background-color", "#00C0C0");
                    break;
                case 8:
                    tr.Style.Add("background-color", "#bfbfbf");
                    break;
                default:
                    tr.Style.Add("background-color", "#ffffff");
                    break;
            }
            object[] _value = new object[1];
            _value[0] = Convert.ToInt32(HSpecialPlanId.Value);
            rep.DataSource = new BLL.SpecialPlan().GetSpecialPlanDetailBySpecialIdForList(_value);
            rep.DataBind();


        }
    }

    protected void rptSpecialPlanDetail_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            HiddenField HSpecialPlanId = e.Item.FindControl("HSpecialPlanId") as HiddenField;
            HiddenField Hstate = e.Item.FindControl("Hstate") as HiddenField;
            HtmlTableRow tr = e.Item.FindControl("rowdetail") as HtmlTableRow;
            switch (Convert.ToInt32(Hstate.Value))
            {
                case 4:
                    tr.Style.Add("background-color", "#00C0C0");
                    break;
                case 5:
                    tr.Style.Add("background-color", "#00C000");
                    break;
                case 6:
                    tr.Style.Add("background-color", "#ffff00");
                    break;
                case 7:
                    tr.Style.Add("background-color", "#00C0C0");
                    break;
                case 8:
                    tr.Style.Add("background-color", "#bfbfbf");
                    break;
                default:
                    tr.Style.Add("background-color", "#ffffff");
                    break;
            }
        }
    }


    protected void rptSpecialPlan_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "DownLoad")
        {
            string path = e.CommandArgument.ToString();
            Response.Write(path);
            FileDownload(path);
        }
    }


    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnModify_Click(object sender, EventArgs e)
    {
        int count = 0;
        int SpecialPlanId = 0;
        foreach (RepeaterItem item in this.rptSpecialPlan.Items)
        {
            CheckBox ckb = item.FindControl("ckbSelect") as CheckBox;
            if (ckb.Checked)
            {
                count++;
                HiddenField HSpecialPlanId = item.FindControl("HSpecialPlanId") as HiddenField;
                SpecialPlanId = Convert.ToInt32(HSpecialPlanId.Value);
            }
        }
        if (count == 1)
        {
            string _url = "ModifySpecialPlan.aspx?Id=" + SpecialPlanId + "&url=SpecialPlanDisplany.aspx&Department=" + this.drpDepartment.SelectedValue;
            Page.RegisterStartupScript("windowopen", "<script>window.open('" + _url + "','','height=200,width=1200,top=300,left=220,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
            return;
        }
        if (count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个！", Page);
            return;
        }
        if (count == 0)
        {
            Utility.HttpHelp.alert("请至少选择一个！", Page);
            return;
        }
    }

    /// <summary>
    /// reapeater事件
    /// </summary>
    /// <param name="source"></param>
    /// <param name="e"></param>
    protected void rptSpecialPlanDetail_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        HiddenField HSpecialPlanDetailSortId = e.Item.FindControl("HSpecialPlanDetailSortId") as HiddenField;
        HiddenField HSpecialPlanId = e.Item.FindControl("HSpecialPlanId") as HiddenField;
        string SpecialPlanDetailId = e.CommandArgument.ToString();
        string SpecialPlanDetailSortId = HSpecialPlanDetailSortId.Value;
        if (e.CommandName == "Modify")
        {
            string _url = "ModifySpecialPlanDetail.aspx?url=SpecialPlanDisplany.aspx&SpecialPlanDetailId=" + SpecialPlanDetailId + "&SpecialPlanDetailSortId=" + SpecialPlanDetailSortId + "&SpecialPlanId=" + HSpecialPlanId.Value + "&Department=" + this.drpDepartment.SelectedValue;
            Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','ModifyQuarterPlanResolveDetail','height=200,width=900,top=400,left=80,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
        }
        if (e.CommandName == "Delete")
        {
            int val = new BLL.SpecialPlan().DelDetailById(new object[] { Convert.ToInt32(SpecialPlanDetailId) });
            if (val > 0)
            {
                Utility.HttpHelp.alert("删除成功！", Page);
                bindGridView();
                return;
            }
        }
    }


    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDel_Click(object sender, EventArgs e)
    {
        int count = 0;
        int SpecialPlanId = 0;
        List<object[]> _valueList = new List<object[]>();
        foreach (RepeaterItem item in this.rptSpecialPlan.Items)
        {
            CheckBox ckb = item.FindControl("ckbSelect") as CheckBox;
            if (ckb.Checked)
            {
                count++;
                HiddenField HSpecialPlanId = item.FindControl("HSpecialPlanId") as HiddenField;
                SpecialPlanId = Convert.ToInt32(HSpecialPlanId.Value);
                _valueList.Add(new object[] { SpecialPlanId });
            }
        }
        if (count >= 1)
        {
            int val = new BLL.SpecialPlan().DelById(_valueList);
            if (val > 0)
            {
                Utility.HttpHelp.alert("删除成功！", Page);
                bindGridView();
                return;
            }
        }

        if (count == 0)
        {
            Utility.HttpHelp.alert("请至少选择一个！", Page);
            return;
        }
    }
}